package jwt

import (
	"ia/common/model/admin"
	"ia/common/support/global"
	"time"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/jwt"
)

var SigKey = []byte("signature_hmac_secret_shared_key")

// Serve the middleware's action
func ServeHTTP(ctx iris.Context) (err error) {

	// exact header token
	token := jwt.FromHeader(ctx)
	if token == "" {
		ctx.StopWithError(iris.StatusUnauthorized, jwt.ErrMissing)
		return
	}

	vToken, err := jwt.Verify(jwt.HS256, SigKey, []byte(token))
	if err != nil {
		ctx.StopWithError(iris.StatusUnauthorized, err)
		return
	}

	claims := admin.AdminUser{}
	if err = vToken.Claims(&claims); err != nil {
		ctx.StopWithError(iris.StatusUnauthorized, err)
		return
	}

	// verify
	// TODO
	// standardClaims := jwt.GetVerifiedToken(ctx).StandardClaims
	// expiresAtString := standardClaims.ExpiresAt().Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
	// timeLeft := standardClaims.Timeleft()

	// token缓存
	// TODO 缓存到redis
	ctx.Values().Set(global.Uid, claims.Id)
	ctx.Values().Set(global.User, claims)
	return nil
}

func GenerateToken[T any](t T) (string, error) {
	// expireTime := time.Now().Add(time.Duration(global.GConfig.App.Own.JWTTimeout) * time.Minute)
	// signer := jwt.NewSigner(jwt.HS256, SigKey, time.Duration(global.GConfig.App.Own.JWTTimeout))
	signer := jwt.NewSigner(jwt.HS256, SigKey, time.Hour*6)

	token, err := signer.Sign(t)
	return string(token), err
}
